package cn.lixin.org.service.impl;

import cn.lixin.basic.service.impl.BaseServiceImpl;
import cn.lixin.org.domain.Department;
import cn.lixin.org.mapper.DepartmentMapper;
import cn.lixin.org.query.DepartmentQuery;
import cn.lixin.basic.utils.PageList;
import cn.lixin.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 添加
     *
     * @param department
     */
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);// 先保存，有自增id才可以获取id
        this.update(department);

    }

    /**
     * 修改
     *
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        // 添加顶级父类
        if (department.getParent() == null){
            dirPath ="/" + department.getId(); // dirPath:/id
        }else {
            // 添加子部门
            Department parentDept = departmentMapper.loadById(department.getParent().getId()); // 查询父类对象
            dirPath = parentDept.getDirPath() + "/" + department.getId();
        }
        // 重新设置dirPath
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }



    /**
     * 查询所有部门
     */
    @Override
    public List<Department> loadTree() {
        return departmentMapper.loadTree();
    }


}
